package com.itheima.tliasmanagement.controller;

import com.itheima.tliasmanagement.aop.MyLog;
import com.itheima.tliasmanagement.dto.AddDeptDto;
import com.itheima.tliasmanagement.dto.UpdateDeptDto;
import com.itheima.tliasmanagement.entity.Dept;
import com.itheima.tliasmanagement.service.DeptService;
import com.itheima.tliasmanagement.vo.DeptVo;
import com.itheima.tliasmanagement.vo.Result2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;

    //1. 接收参数
    @GetMapping
    @CrossOrigin(origins = "http://127.0.0.1:5173")
    public Result2<List<DeptVo>> depts(HttpServletRequest request){
        //2. 调用service完成业务逻辑处理
        List<DeptVo> depts = deptService.depts();
        //3. 返回响应数据
        return Result2.ok(depts);
    }

    /**
     * 1. HttpServletRequest.getParameter("参数名")
     * 2. @RequestParam("参数名")
     * 3. controller的形参与前端传递参数名保持一致
     * */
    @MyLog(desc="删除部门")
    @DeleteMapping
    //public Result2<Void> deleteById(HttpServletRequest request){
    public Result2<Void> deleteById(@RequestParam("id")Integer id){
    //public Result2<Void> deleteById(Integer deptId, String name){
        deptService.deleteById(id);
        return Result2.ok();
    }

    /***
     * @RequestBody 前端是post或者put、delete传递json格式的参数
     * 新增部门
     */
    @MyLog(desc="新增部门")
    @PostMapping
    public Result2 addDept(@RequestBody AddDeptDto dto){
        // 调用service完成业务逻辑
        deptService.addDept(dto);
        //int i = 1/0;
        // 返回结果
        return Result2.ok();
    }

    /**
     *
     * 路径变量  路径参数
     * @PathVariable
     *
     * 根据id获取部门
     */
    @GetMapping("/{id}")
    public Result2<Dept> getById(@PathVariable("id")Integer id){
        // 调用service完成业务逻辑
        Dept dept = deptService.getById(id);
        // 返回结果
        return Result2.ok(dept);
    }

    /**、
     * 修改部门
     * */
    @MyLog(desc="修改部门")
    @PutMapping
    public Result2 updateDept(@RequestBody UpdateDeptDto dto){
        // 调用service完成业务逻辑
        deptService.updateDept(dto);
        // 返回结果
        return Result2.ok();
    }


}
